package com.hp_dzzl.mixin.jerotesvillage.entity.boss;

import com.jerotes.jerotes.util.AttackFind;
import com.jerotes.jerotes.util.EntityAndItemFind;
import com.jerotes.jerotes.util.Main;
import com.jerotes.jerotesvillage.entity.Animal.DracognathusEntity;
import com.jerotes.jerotesvillage.entity.Boss.Biome.CorrosiverEntity;
import com.jerotes.jerotesvillage.entity.Monster.BitterColdWindEntity;
import com.jerotes.jerotes.init.JerotesMobEffects;
import com.jerotes.jerotesvillage.init.JerotesVillageBlocks;
import com.jerotes.jerotesvillage.init.JerotesVillageSounds;
import net.minecraft.core.BlockPos;
import net.minecraft.core.particles.BlockParticleOption;
import net.minecraft.core.particles.ParticleTypes;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.sounds.SoundEvent;
import net.minecraft.sounds.SoundSource;
import net.minecraft.util.Mth;
import net.minecraft.world.Difficulty;
import net.minecraft.world.effect.MobEffect;
import net.minecraft.world.effect.MobEffectInstance;
import net.minecraft.world.effect.MobEffects;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.entity.EntityType;
import net.minecraft.world.entity.LivingEntity;
import net.minecraft.world.entity.ai.attributes.Attributes;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.phys.AABB;
import net.minecraft.world.phys.Vec3;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Overwrite;

import java.util.List;

@Mixin(value = CorrosiverEntity.class, remap = false)
public abstract class CorrosiverEntityMixin {

    /**
     * @author <你的名字或ID>
     * @reason 完整重写 trueHurt 方法以进行自定义修改
     */
    @Overwrite
    public boolean trueHurt() {
        ServerLevel serverLevel;
        // 播放攻击音效
        if (!((CorrosiverEntity) (Object) this).isSilent()) {
            ((CorrosiverEntity) (Object) this).level().playSound(
                    null,
                    ((CorrosiverEntity) (Object) this).getX(),
                    ((CorrosiverEntity) (Object) this).getY(),
                    ((CorrosiverEntity) (Object) this).getZ(),
                    JerotesVillageSounds.CORROSIVER_ATTACK,
                    ((CorrosiverEntity) (Object) this).getSoundSource(),
                    10.0f,
                    0.8f + ((CorrosiverEntity) (Object) this).getRandom().nextFloat() * 0.4f
            );
        }

        // 根据难度设置效果等级
        int levels = 0;
        if (((CorrosiverEntity) (Object) this).level().getDifficulty() == Difficulty.NORMAL) {
            levels = 1;
        } else if (((CorrosiverEntity) (Object) this).level().getDifficulty() == Difficulty.HARD) {
            levels = 2;
        }

        // 根据攻击类型设置基础伤害和击退
        float damageBase = 1.0f;
        float knockbackBase = 1.0f;
        if (((CorrosiverEntity) (Object) this).getAttackUse() == 1) {
            damageBase = 1.5f;
            knockbackBase = 0.75f;
        }
        if (((CorrosiverEntity) (Object) this).getAttackUse() == 2) {
            damageBase = 1.0f;
            knockbackBase = 1.25f;
        }
        if (((CorrosiverEntity) (Object) this).getAttackUse() == 3) {
            damageBase = 1.15f;
            knockbackBase = 1.15f;
        }
        if (((CorrosiverEntity) (Object) this).getAttackUse() == 4) {
            damageBase = 1.25f;
            knockbackBase = 1.05f;
        }
        if (((CorrosiverEntity) (Object) this).getAttackUse() == 5) {
            damageBase = 1.0f;
            knockbackBase = 2.0f;
        }

        // 基于攻击伤害属性和下落距离调整伤害
        if (((CorrosiverEntity) (Object) this).getAttribute(Attributes.ATTACK_DAMAGE) != null) {
            damageBase += Math.max(
                    0.0f,
                    Math.min(
                            3.0f,
                            (float) ((double) ((float) (
                                    (double) (Math.min(6.0f, 2.0f * ((CorrosiverEntity) (Object) this).fallDistance) +
                                            Math.min(8.0f, ((CorrosiverEntity) (Object) this).fallDistance)
                                    )) + 1.0 * (double) ((CorrosiverEntity) (Object) this).fallDistance)) /
                                    ((CorrosiverEntity) (Object) this).getAttributeValue(Attributes.ATTACK_DAMAGE)
                    )
            );
        }

        // 获取攻击范围内的实体
        List<LivingEntity> list = ((CorrosiverEntity) (Object) this).level().getEntitiesOfClass(
                LivingEntity.class,
                new AABB(
                        ((CorrosiverEntity) (Object) this).getX() - 1.0,
                        ((CorrosiverEntity) (Object) this).getY() - 1.0,
                        ((CorrosiverEntity) (Object) this).getZ() - 1.0,
                        ((CorrosiverEntity) (Object) this).getX() + 1.0,
                        ((CorrosiverEntity) (Object) this).getY() + 1.0,
                        ((CorrosiverEntity) (Object) this).getZ() + 1.0
                ).inflate(0.75, 0.75, 0.75)
        );

        // 遍历攻击范围内的实体
        for (LivingEntity hurt : list) {
            Level level;
            DracognathusEntity dracognathusEntity;
            CorrosiverEntity corrosiverEntity;
            BitterColdWindEntity bitterColdWindEntity;

            // 攻击判定条件过滤
            if (hurt == null
                    || AttackFind.FindCanNotAttack((LivingEntity) ((CorrosiverEntity) (Object) this), (Entity) hurt)
                    || !((CorrosiverEntity) (Object) this).hasLineOfSight((Entity) hurt)
                    || (!Main.canSee((Entity) hurt, (Entity) ((CorrosiverEntity) (Object) this)) && ((CorrosiverEntity) (Object) this).getAttackUse() != 4)
                    || (hurt instanceof BitterColdWindEntity && (bitterColdWindEntity = (BitterColdWindEntity) hurt).getTarget() != ((CorrosiverEntity) (Object) this) && ((CorrosiverEntity) (Object) this).getTarget() != bitterColdWindEntity)
                    || (hurt instanceof CorrosiverEntity && (corrosiverEntity = (CorrosiverEntity) hurt).getTarget() != ((CorrosiverEntity) (Object) this) && ((CorrosiverEntity) (Object) this).getTarget() != corrosiverEntity)
                    || (hurt instanceof DracognathusEntity && (dracognathusEntity = (DracognathusEntity) hurt).getTarget() != ((CorrosiverEntity) (Object) this) && ((CorrosiverEntity) (Object) this).getTarget() != dracognathusEntity)) {
                continue;
            }

            // 执行攻击逻辑
            AttackFind.attackBegin((LivingEntity) ((CorrosiverEntity) (Object) this), (Entity) hurt);
            boolean bl2 = AttackFind.attackAfter(
                    (LivingEntity) ((CorrosiverEntity) (Object) this),
                    (Entity) hurt,
                    (float) damageBase,
                    (float) knockbackBase,
                    false,
                    0.0f
            );

            if (!bl2) {
                continue;
            }

            // 计算击退抗性
            double d = 0.0;
            if (hurt.getAttribute(Attributes.KNOCKBACK_RESISTANCE) != null) {
                d = Math.max(hurt.getAttributeValue(Attributes.KNOCKBACK_RESISTANCE), 1.0);
            }

            // 生成粒子效果（服务端）
            if ((level = hurt.level()) instanceof ServerLevel) {
                ServerLevel serverLevel2 = (ServerLevel) level;
                Vec3 vec3 = hurt.position().subtract(((CorrosiverEntity) (Object) this).position());
                BlockPos blockPos = hurt.getOnPos();
                Vec3 vec33 = blockPos.getCenter().add(0.0, 0.5, 0.0);
                int n = (int) (100.0 * d);

                // 地面方块粒子
                serverLevel2.sendParticles(
                        new BlockParticleOption(ParticleTypes.BLOCK, serverLevel2.getBlockState(blockPos)),
                        vec33.x,
                        vec33.y,
                        vec33.z,
                        n,
                        0.3,
                        0.3,
                        0.3,
                        0.15
                );

                // 冰岩方块粒子
                serverLevel2.sendParticles(
                        new BlockParticleOption(ParticleTypes.BLOCK, ((Block) JerotesVillageBlocks.ICE_ROCK.get()).defaultBlockState()),
                        vec3.x,vec3.y,vec3.z,
                        n,
                        0.3,
                        0.3,
                        0.3,
                        0.15
                );

                // 雪花粒子
                serverLevel2.sendParticles(
                        ParticleTypes.SNOWFLAKE,
                        vec33.x,
                        ((CorrosiverEntity) (Object) this).getRandomY(),
                        vec33.z,
                        16,
                        0.3,
                        0.3,
                        0.3,
                        0.15
                );
            }

            // 计算击退强度
            double d3 = Math.max(0.0, 1.0 - d) + (double) (knockbackBase / 2.0f);

            // 应用击退效果（针对特定尺寸实体）
            if ((Main.mobSizeSmall((Entity) hurt) || Main.mobSizeMedium((Entity) hurt) || Main.mobSizeLarge((Entity) hurt))
                    && !EntityAndItemFind.isNoSpecialKnockback((EntityType<?>) hurt.getType())) {

                hurt.setOnGround(false);

                // 攻击类型5额外向上击退
                if (((CorrosiverEntity) (Object) this).getAttackUse() == 5) {
                    hurt.setDeltaMovement(hurt.getDeltaMovement().add(0.0, 2.0, 0.0));
                }

                // 非风状态击退
                if (!((CorrosiverEntity) (Object) this).isWind()) {
                    hurt.setDeltaMovement(hurt.getDeltaMovement().add(
                            -(((CorrosiverEntity) (Object) this).getX() - hurt.getX()) * 1.4 * d3 * (0.7 + (double) (knockbackBase / 3.0f)),
                            -(((CorrosiverEntity) (Object) this).getY() - hurt.getY()) * 2.0 * d3 * (0.7 + (double) (knockbackBase / 3.0f)),
                            -(((CorrosiverEntity) (Object) this).getZ() - hurt.getZ()) * 1.4 * d3 * (0.7 + (double) (knockbackBase / 3.0f))
                    ));
                }
                // 风状态额外增强击退
                else {
                    hurt.setDeltaMovement(hurt.getDeltaMovement().add(
                            -(((CorrosiverEntity) (Object) this).getX() - hurt.getX()) * 1.4 * (d3 * (0.7 + (double) (knockbackBase / 3.0f)) + 0.3),
                            -(((CorrosiverEntity) (Object) this).getY() - hurt.getY()) * 2.0 * (d3 * (0.7 + (double) (knockbackBase / 3.0f)) + 0.35),
                            -(((CorrosiverEntity) (Object) this).getZ() - hurt.getZ()) * 1.4 * (d3 * (0.7 + (double) (knockbackBase / 3.0f)) + 0.3)
                    ));
                }
            }

            // 设置冻结时间
            if (hurt.getTicksFrozen() < (((CorrosiverEntity) (Object) this).isWind() ? 420 : 280)) {
                hurt.setTicksFrozen(((CorrosiverEntity) (Object) this).isWind() ? 420 : 280);
            }

            // 服务端添加效果
            if (hurt.level().isClientSide()) {
                continue;
            }

            // 腐蚀效果
            hurt.addEffect(
                    new MobEffectInstance(
                            (MobEffect) JerotesMobEffects.CORROSIVE.get(),
                            ((CorrosiverEntity) (Object) this).isWind() ? 400 : 200,
                            levels
                    ),
                    (Entity) ((CorrosiverEntity) (Object) this)
            );

            // 风状态额外添加虚弱和减速
            if (((CorrosiverEntity) (Object) this).isWind()) {
                hurt.addEffect(
                        new MobEffectInstance(MobEffects.WEAKNESS, 200, 0),
                        (Entity) ((CorrosiverEntity) (Object) this)
                );
                hurt.addEffect(
                        new MobEffectInstance(MobEffects.MOVEMENT_SLOWDOWN, 200, 0),
                        (Entity) ((CorrosiverEntity) (Object) this)
                );
            }
        }

        // 攻击类型1和4的额外效果（地面粒子、音效）
        if (((CorrosiverEntity) (Object) this).getAttackUse() == 1 || ((CorrosiverEntity) (Object) this).getAttackUse() == 4) {
            Level level = ((CorrosiverEntity) (Object) this).level();
            if (level instanceof ServerLevel) {
                serverLevel = (ServerLevel) level;
                SoundEvent soundEvent = ((CorrosiverEntity) (Object) this).getAttackUse() == 1
                        ? JerotesVillageSounds.MACE_SMASH_GROUND_HEAVY
                        : JerotesVillageSounds.MACE_SMASH_GROUND;

                Vec3 vec3 = ((CorrosiverEntity) (Object) this).getOnPos().getCenter().add(0.0, 0.5, 0.0);
                int n = (int) (250.0f);
                //下面是上一行的原逻辑，注释掉了
                //int n = (int) (50.0f * ((CorrosiverEntity) (Object) this).getHealth());
                BlockState blockState = ((CorrosiverEntity) (Object) this).level().getBlockState(((CorrosiverEntity) (Object) this).getOnPos());

                // 地面方块粒子
                serverLevel.sendParticles(
                        new BlockParticleOption(ParticleTypes.BLOCK, blockState),
                        vec3.x,vec3.y,vec3.z,
                        n, 0.3, 0.3, 0.3, 0.15
                );

                // 冰岩方块粒子
                serverLevel.sendParticles(
                        new BlockParticleOption(ParticleTypes.BLOCK, ((Block) JerotesVillageBlocks.ICE_ROCK.get()).defaultBlockState()),
                        vec3.x,vec3.y,vec3.z,
                        n, 0.3, 0.3, 0.3, 0.15
                );

                // 播放撞击地面音效
                if (!((CorrosiverEntity) (Object) this).isSilent()) {
                    serverLevel.playSound(
                            null,
                            ((CorrosiverEntity) (Object) this).getX(),
                            ((CorrosiverEntity) (Object) this).getY(),
                            ((CorrosiverEntity) (Object) this).getZ(),
                            soundEvent,
                            SoundSource.NEUTRAL,
                            10.0f,
                            1.0f
                    );
                }

                BlockPos blockPos = ((CorrosiverEntity) (Object) this).getOnPos();
                Vec3 vec33 = blockPos.getCenter().add(0.0, 0.5, 0.0);

                // 额外地面粒子
                serverLevel.sendParticles(
                        new BlockParticleOption(ParticleTypes.BLOCK, serverLevel.getBlockState(blockPos)),
                        vec33.x,
                        vec33.y,
                        vec33.z,
                        32,
                        0.3,
                        0.3,
                        0.3,
                        0.15
                );

                // 额外雪花粒子
                serverLevel.sendParticles(
                        ParticleTypes.SNOWFLAKE,
                        vec33.x,
                        ((CorrosiverEntity) (Object) this).getRandomY(),
                        vec33.z,
                        32,
                        0.3,
                        0.3,
                        0.3,
                        0.15
                );
            }

            // 环形雪花粒子效果
            for (int j = 0; j < 5; ++j) {
                for (int i = 0; i < 24; ++i) {
                    // 内层雪花
                    double angle = Math.PI * 2 * (double) i / 24.0;
                    double radius = Main.mobWidth((Entity) ((CorrosiverEntity) (Object) this)) * 1.25f;
                    double offsetX = Math.cos(angle) * radius;
                    double offsetZ = Math.sin(angle) * radius;

                    ((CorrosiverEntity) (Object) this).level().addParticle(
                            ParticleTypes.SNOWFLAKE,
                            ((CorrosiverEntity) (Object) this).getX() + offsetX,
                            ((CorrosiverEntity) (Object) this).getY(0.0) + (double) j * 0.25,
                            ((CorrosiverEntity) (Object) this).getZ() + offsetZ,
                            0.0,
                            0.12,
                            0.0
                    );

                    // 外层雪花
                    double angle2 = Math.PI * 2 * (double) i / 24.0;
                    double radius2 = Main.mobWidth((Entity) ((CorrosiverEntity) (Object) this)) * 2.75f;
                    double offsetX2 = Math.cos(angle2) * radius2;
                    double offsetZ2 = Math.sin(angle2) * radius2;

                    ((CorrosiverEntity) (Object) this).level().addParticle(
                            ParticleTypes.SNOWFLAKE,
                            ((CorrosiverEntity) (Object) this).getX() + offsetX2,
                            ((CorrosiverEntity) (Object) this).getY(0.0) + (double) j * 0.15,
                            ((CorrosiverEntity) (Object) this).getZ() + offsetZ2,
                            0.0,
                            0.12,
                            0.0
                    );
                }
            }
        }

        // 攻击类型1、3、4添加震动效果
        if (((CorrosiverEntity) (Object) this).getAttackUse() == 1 || ((CorrosiverEntity) (Object) this).getAttackUse() == 3 || ((CorrosiverEntity) (Object) this).getAttackUse() == 4) {

            List<LivingEntity> listShake = ((CorrosiverEntity) (Object) this).level().getEntitiesOfClass(
                    LivingEntity.class,
                    ((CorrosiverEntity) (Object) this).getBoundingBox().inflate(16.0, 16.0, 16.0)
            );

            for (LivingEntity shake : listShake) {
                if (shake == null
                        || shake == ((CorrosiverEntity) (Object) this)
                        || ((CorrosiverEntity) (Object) this).distanceToSqr((Entity) shake) > Double.MAX_VALUE
                        || shake.level().isClientSide()) {
                    continue;
                }

                shake.addEffect(
                        new MobEffectInstance(
                                (MobEffect) JerotesMobEffects.QUAKE.get(),
                                20,
                                0,
                                false,
                                false
                        ),
                        (Entity) ((CorrosiverEntity) (Object) this)
                );
            }
        }

        // 横扫攻击
        Main.sweepAttack((Entity) ((CorrosiverEntity) (Object) this));

        // 攻击类型1和4的落块效果
        Level i = ((CorrosiverEntity) (Object) this).level();
        if (i instanceof ServerLevel) {
            serverLevel = (ServerLevel) i;
            if (((CorrosiverEntity) (Object) this).getAttackUse() == 1 || ((CorrosiverEntity) (Object) this).getAttackUse() == 4) {
                AABB aabb = AABB.ofSize(
                        new Vec3(
                                ((CorrosiverEntity) (Object) this).getX(),
                                ((CorrosiverEntity) (Object) this).getY() - 1.0,
                                ((CorrosiverEntity) (Object) this).getZ()
                        ),
                        (double) (Main.mobWidth((Entity) ((CorrosiverEntity) (Object) this)) / 2.0f + 2.0f),
                        0.0,
                        (double) (Main.mobWidth((Entity) ((CorrosiverEntity) (Object) this)) / 2.0f + 2.0f)
                );

                // 生成下落方块
                for (BlockPos blockPos : BlockPos.betweenClosed(
                        (int) Mth.floor((double) aabb.minX),
                        (int) Mth.floor((double) aabb.minY),
                        (int) Mth.floor((double) aabb.minZ),
                        (int) Mth.floor((double) aabb.maxX),
                        (int) Mth.floor((double) aabb.maxY),
                        (int) Mth.floor((double) aabb.maxZ)
                )) {
                    Main.spawnFallingBlockByPos((ServerLevel) serverLevel, (BlockPos) blockPos);
                }
            }
        }

        // ===================== 新增的调试消息功能 =====================
        // 仅在服务端执行，避免客户端报错
        if (((CorrosiverEntity) (Object) this).level() instanceof ServerLevel) {
            // 1. 获取以攻击者为中心，16格为半径范围内的所有玩家
            List<Player> nearbyPlayers = ((CorrosiverEntity) (Object) this).level().getEntitiesOfClass(
                    Player.class,
                    ((CorrosiverEntity) (Object) this).getBoundingBox().inflate(16.0D) // 16格范围
            );

            // 2. 构建调试消息内容
            String attackType = "未知";
            switch (((CorrosiverEntity) (Object) this).getAttackUse()) {
                case 1:
                    attackType = "重击";
                    break;
                case 2:
                    attackType = "击退";
                    break;
                case 3:
                    attackType = "震击";
                    break;
                case 4:
                    attackType = "横扫";
                    break;
                case 5:
                    attackType = "上挑";
                    break;
            }
            String message = String.format("[调试] Corrosiver 发动了攻击！类型: %s, 基础伤害: %.2f, 基础击退: %.2f",
                    attackType, damageBase, knockbackBase);

            // 3. 向每个玩家发送消息
            for (Player player : nearbyPlayers) {
                //player.sendSystemMessage(Component.literal(message));
            }
        }
        // ============================================================

        return true;
    }
}